
use volatile::Volatile;
use core::fmt;
use lazy_static::lazy_static;
use spin::Mutex;

/// 标准VGA文本模式的显存地址
const VGA_BUFFER: *mut Volatile<u16> = 0xB8000 as *mut Volatile<u16>;

/// VGA文本模式的颜色枚举
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Color {
    Black = 0,
    Blue = 1,
    Green = 2,
    Cyan = 3,
    Red = 4,
    Magenta = 5,
    Brown = 6,
    LightGray = 7,
    DarkGray = 8,
    LightBlue = 9,
    LightGreen = 10,
    LightCyan = 11,
    LightRed = 12,
    Pink = 13,
    Yellow = 14,
    White = 15,
}

/// 组合前景色和背景色的属性字节
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct ColorCode(u8);

impl ColorCode {
    /// 创建一个新的颜色属性字节
    pub const fn new(foreground: Color, background: Color) -> ColorCode {
        ColorCode((background as u8) << 4 | (foreground as u8))
    }
}

/// 屏幕上的一个字符及其属性
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct ScreenChar {
    pub ascii_character: u8,
    pub color_code: ColorCode,
}

/// 文本缓冲区的宽度和高度
pub const BUFFER_WIDTH: usize = 80;
pub const BUFFER_HEIGHT: usize = 25;

/// 文本缓冲区结构体
#[repr(transparent)]
pub struct Buffer {
    pub chars: [[Volatile<ScreenChar>; BUFFER_WIDTH]; BUFFER_HEIGHT],
}

lazy_static! {
    /// 全局的VGA文本缓冲区
    pub static ref WRITER: Mutex<Writer> = Mutex::new(Writer {
        column_position: 0,
        row_position: 0,
        color_code: ColorCode::new(Color::Yellow, Color::Black),
        buffer: unsafe { &mut *(VGA_BUFFER as *mut Buffer) },
        cursor_visible: true,
        last_chars: [ScreenChar {
            ascii_character: 0,
            color_code: ColorCode::new(Color::Black, Color::Black)
        }; 256],
        last_chars_count: 0,
    });
}

/// 文本写入器
pub struct Writer {
    column_position: usize,
    row_position: usize,
    color_code: ColorCode,
    buffer: &'static mut Buffer,
    cursor_visible: bool,
    last_chars: [ScreenChar; 256],
    last_chars_count: usize,
}

/// 光标位置信息
#[derive(Debug, Clone, Copy)]
pub struct CursorPosition {
    pub row: usize,
    pub column: usize,
    pub visible: bool,
    pub blink: bool,
}

impl Writer {
    /// 设置文本颜色
    pub fn set_color(&mut self, foreground: Color, background: Color) {
        self.color_code = ColorCode::new(foreground, background);
    }

    /// 获取当前光标位置
    pub fn cursor_position(&self) -> CursorPosition {
        CursorPosition {
            row: self.row_position,
            column: self.column_position,
            visible: self.cursor_visible,
            blink: false,
        }
    }

    /// 清屏
    pub fn clear_screen(&mut self) {
        for row in 0..BUFFER_HEIGHT {
            self.clear_row(row);
        }
        self.column_position = 0;
        self.row_position = 0;
    }

    /// 设置光标位置
    pub fn set_cursor_position(&mut self, position: CursorPosition) {
        self.row_position = position.row.min(BUFFER_HEIGHT - 1);
        self.column_position = position.column.min(BUFFER_WIDTH - 1);
    }

    /// 显示/隐藏光标
    pub fn set_cursor_visibility(&mut self, visible: bool) {
        self.cursor_visible = visible;
        self.update_cursor();
    }

    /// 设置光标闪烁状态
    pub fn set_cursor_blink(&mut self, blink: bool) {
        let position = self.cursor_position();
        let mut new_position = position;
        new_position.blink = blink;
        self.set_cursor_position(new_position);
    }

    /// 更新光标显示状态
    fn update_cursor(&mut self) {
        // TODO: 实际实现光标显示/隐藏和闪烁逻辑
    }

    /// 退格操作 - 删除光标前的字符并向后移动光标
    pub fn backspace(&mut self) {
        if self.column_position > 0 {
            // 在同一行内退格
            self.column_position -= 1;
            let blank = ScreenChar {
                ascii_character: b' ',
                color_code: self.color_code,
            };
            self.buffer.chars[self.row_position][self.column_position].write(blank);
        } else if self.row_position > 0 {
            // 跳到上一行的末尾
            self.row_position -= 1;
            self.column_position = BUFFER_WIDTH - 1;
            
            // 从行末向前查找最后一个非空字符
            while self.column_position > 0 {
                let current_char = self.buffer.chars[self.row_position][self.column_position].read();
                if current_char.ascii_character != b' ' {
                    self.column_position += 1;
                    break;
                }
                self.column_position -= 1;
            }
            
            // 如果整行都是空格，光标停在行首
            if self.column_position == 0 {
                let first_char = self.buffer.chars[self.row_position][0].read();
                if first_char.ascii_character == b' ' {
                    self.column_position = 0;
                }
            }
        }
    }

    /// Delete操作 - 删除光标位置的字符，后面的字符向前移动
    pub fn delete(&mut self) {
        // 从光标位置开始，将后面的字符向前移动
        let row = self.row_position;
        let start_col = self.column_position;
        
        // 在当前行内向前移动字符
        for col in start_col..(BUFFER_WIDTH - 1) {
            let next_char = self.buffer.chars[row][col + 1].read();
            self.buffer.chars[row][col].write(next_char);
        }
        
        // 检查是否需要从下一行拉取字符
        if row < BUFFER_HEIGHT - 1 {
            let next_row_first_char = self.buffer.chars[row + 1][0].read();
            // 如果下一行不是空行，将第一个字符移动到当前行末尾
            if next_row_first_char.ascii_character != b' ' || 
               self.is_line_not_empty(row + 1) {
                self.buffer.chars[row][BUFFER_WIDTH - 1].write(next_row_first_char);
                
                // 将下一行的所有字符向前移动
                for col in 0..(BUFFER_WIDTH - 1) {
                    let next_char = self.buffer.chars[row + 1][col + 1].read();
                    self.buffer.chars[row + 1][col].write(next_char);
                }
                
                // 清空下一行的最后一个位置
                let blank = ScreenChar {
                    ascii_character: b' ',
                    color_code: self.color_code,
                };
                self.buffer.chars[row + 1][BUFFER_WIDTH - 1].write(blank);
            }
        } else {
            // 如果是最后一行，直接清空最后一个位置
            let blank = ScreenChar {
                ascii_character: b' ',
                color_code: self.color_code,
            };
            self.buffer.chars[row][BUFFER_WIDTH - 1].write(blank);
        }
    }

    /// 检查指定行是否不为空（包含非空格字符）
    fn is_line_not_empty(&self, row: usize) -> bool {
        if row >= BUFFER_HEIGHT {
            return false;
        }
        
        for col in 0..BUFFER_WIDTH {
            let char_data = self.buffer.chars[row][col].read();
            if char_data.ascii_character != b' ' {
                return true;
            }
        }
        false
    }

    /// 撤回最后输出的字符（基于历史记录）
    pub fn undo_last_char(&mut self) {
        if self.last_chars_count > 0 {
            self.last_chars_count -= 1;
            self.backspace();
        }
    }

    /// 保存字符到历史记录
    fn save_char_to_history(&mut self, screen_char: ScreenChar) {
        if self.last_chars_count < self.last_chars.len() {
            self.last_chars[self.last_chars_count] = screen_char;
            self.last_chars_count += 1;
        } else {
            // 如果历史记录满了，向前移动数组
            for i in 1..self.last_chars.len() {
                self.last_chars[i - 1] = self.last_chars[i];
            }
            self.last_chars[self.last_chars.len() - 1] = screen_char;
        }
    }

    /// 写入一个ASCII字符
    pub fn write_byte(&mut self, byte: u8) {
        match byte {
            b'\n' => self.new_line(),
            0x08 => self.backspace(),  // ASCII退格字符
            0x7F => self.delete(),     // ASCII删除字符
            byte => {
                if self.column_position >= BUFFER_WIDTH {
                    self.new_line();
                }

                let row = self.row_position;
                let col = self.column_position;

                let screen_char = ScreenChar {
                    ascii_character: byte,
                    color_code: self.color_code,
                };

                // 保存到历史记录
                self.save_char_to_history(screen_char);

                self.buffer.chars[row][col].write(screen_char);
                self.column_position += 1;
            }
        }
    }

    /// 清空指定行
    fn clear_row(&mut self, row: usize) {
        let blank = ScreenChar {
            ascii_character: b' ',
            color_code: self.color_code,
        };
        for col in 0..BUFFER_WIDTH {
            self.buffer.chars[row][col].write(blank);
        }
    }

    /// 写入一个字符串
    pub fn write_string(&mut self, s: &str) {
        s.bytes().for_each(|byte| {
            if byte.is_ascii_graphic() || byte == b'\n' || byte == b' ' || byte == 0x08 || byte == 0x7F {
                self.write_byte(byte);
            } else {
                self.write_byte(0xfe);
            }
        });
    }

    /// 换行
    fn new_line(&mut self) {
        self.column_position = 0;
        self.row_position += 1;
        
        if self.row_position >= BUFFER_HEIGHT {
            // 向上滚动一行
            for row in 1..BUFFER_HEIGHT {
                for col in 0..BUFFER_WIDTH {
                    let character = self.buffer.chars[row][col].read();
                    self.buffer.chars[row-1][col].write(character);
                }
            }
            self.clear_row(BUFFER_HEIGHT - 1);
            self.row_position = BUFFER_HEIGHT - 1;
        }
    }
}

impl fmt::Write for Writer {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.write_string(s);
        Ok(())
    }
}

/// 内部打印函数
#[doc(hidden)]
pub fn _print(args: fmt::Arguments) {
    use core::fmt::Write;
    use x86_64::instructions::interrupts;

    interrupts::without_interrupts(|| {
        WRITER.lock().write_fmt(args).unwrap();
    });
}

/// 打印宏，类似于标准库的print!
#[macro_export]
macro_rules! print {
    ($($arg:tt)*) => ($crate::vga::_print(format_args!($($arg)*)));
}

/// 打印宏，类似于标准库的println!
#[macro_export]
macro_rules! println {
    () => ($crate::print!("\n"));
    ($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*)));
}

// 提供公共接口函数
/// 执行退格操作
pub fn backspace() {
    use x86_64::instructions::interrupts;
    interrupts::without_interrupts(|| {
        WRITER.lock().backspace();
    });
}

/// 执行删除操作
pub fn delete() {
    use x86_64::instructions::interrupts;
    interrupts::without_interrupts(|| {
        WRITER.lock().delete();
    });
}

/// 撤销最后一个字符
pub fn undo_last_char() {
    use x86_64::instructions::interrupts;
    interrupts::without_interrupts(|| {
        WRITER.lock().undo_last_char();
    });
}